package com.yixing.tech.entity.entity.attr;

import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.base.ConditionsVO;
import com.yixing.tech.common.utils.DateUtil;
import com.yixing.tech.common.vo.s5.EntitySchema;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yixing tech
 * at 2021/10/9
 * describe：
 */
public final class TimeText extends AttrType {
    public TimeText() {
        super("日期时间", "timeText");
    }

    /**
     * 过滤条件处理
     *
     * @param cond
     */
    @Override
    public void condition(ConditionsVO.Condition cond, EntitySchema.AttrVO attr) throws BusinessException {
        super.condition(cond,attr);
        Object v = cond.getValue();
        if (v instanceof List) {
            List vList = (List) v;
            List<Date> dList = new ArrayList<>();
            for (Object item : vList) {
                dList.add(new Date(Long.parseLong(item.toString())));
            }
            cond.setValue(dList);
        } else if (v instanceof Date) {

        } else {
            cond.setValue(new Date(Long.parseLong(v.toString())));
        }
    }

    /**
     * 数据插入处理
     *
     * @param source
     * @param attr
     * @return
     * @throws BusinessException
     */
    @Override
    public Object in(Object source, EntitySchema.AttrVO attr) throws BusinessException {
        if (!(source instanceof Date)) {
            try {
                long dateTime = Long.parseLong(source.toString());
                source = new Date(dateTime);
            } catch (Exception e) {
                source = DateUtil.praseDate(source.toString(), new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            }
        }
        return super.in(source, attr);
    }
}
